package com.woniuxy.member.app.apiImpl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.cloud.mall95.log.Log;
import com.woniuxy.food.client.foodskuclient.FoodSkuQueryClient;
import com.woniuxy.food.client.result.FoodSkuClientDto;
import com.woniuxy.member.app.apiImpl.util.RequestUtil;
import com.woniuxy.member.client.MemberOrderManageClient;
import com.woniuxy.member.client.param.AddCartParam;
import com.woniuxy.member.client.param.AddStoreOrderParam;
import com.woniuxy.member.client.param.CreatePayOrderParams;
import com.woniuxy.member.client.param.PayOnlineParam;
import com.woniuxy.member.infra.mapper.MemberCouponMapper;
import com.woniuxy.member.infra.model.Member;
import com.woniuxy.member.infra.model.MemberCoupon;
import com.woniuxy.member.service.MemberCouponService;
import com.woniuxy.member.service.MemberService;
import com.woniuxy.orderService.client.CartManageClient;
import com.woniuxy.orderService.client.OrderManageClient;
import com.woniuxy.orderService.client.OrderQueryClient;
import com.woniuxy.orderService.client.param.AddFoodParam;
import com.woniuxy.orderService.client.param.CreatePayOrderParam;
import com.woniuxy.orderService.client.param.CreateStoreOrderParam;
import com.woniuxy.orderService.client.result.PayOrderDto;
import com.woniuxy.store.client.MemberLevelClient;
import com.woniuxy.store.client.StoreInfoClient;
import com.woniuxy.store.client.result.MemberLevelDto;
import com.woniuxy.store.client.result.StoreInfoDto;
import com.woniuxy.table.client.TableQueryClient;
import com.woniuxy.table.client.TableUserRecordQueryClient;
import com.woniuxy.table.client.result.DinnerTableClientDto;
import com.woniuxy.table.client.result.TableClientDto;
import exception.MallException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import result.CommonResultCodeEnum;
import result.Result;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@RequestMapping("/member")
@RestController
public class MemberOrderManageApiImpl implements MemberOrderManageClient {
    @Autowired
    private CartManageClient cartManageClient;
    @Autowired
    private OrderManageClient orderManageClient;
    @Autowired
    private OrderQueryClient orderQueryClient;
    @Autowired
    private FoodSkuQueryClient foodSkuQueryClient;
    @Autowired
    private TableQueryClient tableQueryClient;
    @Autowired
    private StoreInfoClient storeInfoClient;
    @Autowired
    private TableUserRecordQueryClient tableUserRecordQueryClient;
    @Autowired
    private MemberLevelClient memberLevelClient;
    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberCouponService memberCouponService;
    @Autowired
    private MemberCouponMapper memberCouponMapper;

    @Log("用户添加购物车")
    @Override
    public Result addCart(@Valid AddCartParam addCartParam) {
        Result<FoodSkuClientDto> foodSkuClientDtoResult = foodSkuQueryClient.searchFoodSkuById(addCartParam.getSkuId());
        System.out.println(foodSkuClientDtoResult.getData());
        if (foodSkuClientDtoResult.getData() == null) {
            throw new MallException("sku不存在", CommonResultCodeEnum.INVALID_PARAM);
        }
        if (foodSkuClientDtoResult.getData().getSkuState().equals("FORBID")) {
            throw new MallException("菜品未上架", CommonResultCodeEnum.INVALID_PARAM);
        }
        AddFoodParam addFoodParam = BeanUtil.toBean(addCartParam, AddFoodParam.class);
        addFoodParam.setMemberId(RequestUtil.getMemberId());
        addFoodParam.setStoreId(RequestUtil.getStoreId());
        addFoodParam.setTableId(RequestUtil.getTableId());
        Result result = cartManageClient.addFood(addFoodParam);
        return result;
    }

    @Log("用户下订单")
    @Override
    public Result addStoreOrder(@Valid AddStoreOrderParam addStoreOrderParam) {
        CreateStoreOrderParam createStoreOrderParam = BeanUtil.toBean(addStoreOrderParam, CreateStoreOrderParam.class);
        createStoreOrderParam.setStoreId(RequestUtil.getStoreId());
        createStoreOrderParam.setMemberId(RequestUtil.getMemberId());
        createStoreOrderParam.setTableId(RequestUtil.getTableId());
        Result storeOrder = orderManageClient.createStoreOrder(createStoreOrderParam);
        return storeOrder;
    }

    @Log("用户创建大订单")
    @Override
    public Result creatPayOrder(@Valid CreatePayOrderParams createPayOrderParams) {

        Result<TableClientDto> storeTableByTable = tableQueryClient.getStoreTableByTable(RequestUtil.getTableId());
        if (storeTableByTable.getData() == null) {
            throw new MallException("参数异常", CommonResultCodeEnum.INVALID_PARAM);
        }
        CreatePayOrderParam createPayOrderParam = new CreatePayOrderParam();
        createPayOrderParam.setMemberId(RequestUtil.getMemberId());
        createPayOrderParam.setStoreId(RequestUtil.getStoreId());
        createPayOrderParam.setTableId(RequestUtil.getTableId());
        createPayOrderParam.setOrtherFee(storeTableByTable.getData().getFee());

        Result<StoreInfoDto> store = storeInfoClient.getInfoById(RequestUtil.getStoreId());
        createPayOrderParam.setAllTableFee(store.getData().getTableFee());

        Result tableUserRecordByTableId = tableUserRecordQueryClient.getTableUserRecordByTableId(RequestUtil.getTableId());
        createPayOrderParam.setTableUserdRecordId((Integer) tableUserRecordByTableId.getData());
        createPayOrderParam.setIfUseCoupon(createPayOrderParams.getIfUseCoupon());
        createPayOrderParam.setPayWay(createPayOrderParams.getPayWay());

        if (createPayOrderParams.getMemberCouponId().size() != 0 && createPayOrderParams.getMemberCouponId() != null) {
            QueryWrapper<MemberCoupon> queryWrapper = new QueryWrapper<>();
            for (Integer integer : createPayOrderParams.getMemberCouponId()) {
                queryWrapper.eq("member_coupon_id", integer);
            }
            List<MemberCoupon> memberCoupons = memberCouponMapper.selectList(queryWrapper);

            System.out.println(memberCoupons.size());
            System.out.println(createPayOrderParams.getMemberCouponId().size());
            if (memberCoupons.size() != createPayOrderParams.getMemberCouponId().size()) {
                throw new MallException("参数异常", CommonResultCodeEnum.INVALID_PARAM);
            }
            List<Integer> couponId = new ArrayList<>();
            for (MemberCoupon memberCoupon : memberCoupons) {
                if (memberCoupon.getUseState().equals("USED")) {
                    throw new MallException("优惠卷已被使用", CommonResultCodeEnum.INVALID_PARAM);
                }
                couponId.add(memberCoupon.getCouponId());
            }
            createPayOrderParam.setMemberCouponId(couponId);

            Member member = memberService.getById(RequestUtil.getMemberId());
            Result<List<MemberLevelDto>> level = memberLevelClient.getLevelById(RequestUtil.getStoreId());
            for (MemberLevelDto memberLevelDto : level.getData()) {
                if (memberLevelDto.getLevel() == member.getMemberLevel()) {
                    createPayOrderParam.setMemberBenefits(memberLevelDto.getLevelDiscount());
                }
            }
            Result payOrder = orderManageClient.createPayOrder(createPayOrderParam);
            if (payOrder.getFlag()) {
                for (MemberCoupon memberCoupon : memberCoupons) {
                    memberCoupon.setUseState("USED");
                    memberCouponService.updateById(memberCoupon);
                }
            }
            System.out.println(payOrder.getData().toString());
            return payOrder;

        } else if (createPayOrderParams.getMemberCouponId().size() == 0 || createPayOrderParams.getMemberCouponId() == null) {
            createPayOrderParam.setMemberCouponId(null);
            Member member = memberService.getById(RequestUtil.getMemberId());
            Result<List<MemberLevelDto>> level = memberLevelClient.getLevelById(RequestUtil.getStoreId());
            if (level.getData() == null) {
                throw new MallException("参数异常", CommonResultCodeEnum.INVALID_PARAM);
            }
            for (MemberLevelDto memberLevelDto : level.getData()) {
                if (memberLevelDto.getLevel() == member.getMemberLevel()) {
                    createPayOrderParam.setMemberBenefits(memberLevelDto.getLevelDiscount());
                }
            }
            Result payOrder = orderManageClient.createPayOrder(createPayOrderParam);
            if (payOrder.getData() == null) {
                throw new MallException("订单创建失败", CommonResultCodeEnum.INVALID_PARAM);
            }
            System.out.println(payOrder.getData().toString());

            return payOrder;
        }
        return null;
    }

    @Override
    public Result payOnline(@Valid PayOnlineParam payOnlineParam) throws Exception {
        Result<PayOrderDto> payOrderDtoResult = orderQueryClient.queryPayOrderByPayOrderNum(payOnlineParam.getPayOrderNum());
        if (payOrderDtoResult.getData().getPayWay().equals("OFFLINE")) {
            throw new MallException("支付方式有误",CommonResultCodeEnum.INVALID_PARAM);

        }
        orderManageClient.pay(payOnlineParam.getPayOrderNum());
        return Result.success();
    }
}

